import json

import requests
from PySide2.QtCore import QObject, Signal, Qt
from PySide2.QtWidgets import QMessageBox, QTableWidgetItem

from robotController import share


class MySignals(QObject):
    scrollbarOne_signals = Signal(float)
    item_alter_signals = Signal()
    item_click_signals = Signal()
    synchronization_button_signals = Signal()
    refresh_signals = Signal()


class bind:

    def __init__(self, id):

        self.id = id

        self.ui = share.SI.main.ui

        self.flag = 0

        self.processing_dataList = []

        # 实例化
        self.global_ms = MySignals()

        # 源数据
        self.find_original_data_All(id)

        # 信号绑定
        self.global_ms.scrollbarOne_signals.connect(self.original_data_scroll)
        self.global_ms.item_alter_signals.connect(self.item_alter)
        self.global_ms.item_click_signals.connect(self.item_click)
        self.global_ms.synchronization_button_signals.connect(self.synchronization_button)
        self.global_ms.refresh_signals.connect(self.refresh_button)

        # 处理原数据表头
        self.original_data_template()
        # 渲染主体数据
        self.original_data_renderer()

        # # 单元格修改事件
        self.ui.tableWidget.cellChanged.connect(lambda: self.global_ms.item_alter_signals.emit())
        self.ui.tableWidget.cellDoubleClicked.connect(
            lambda: self.global_ms.item_click_signals.emit())

        # 同步按钮绑定
        self.ui.pushButton.clicked.connect(
            lambda: self.global_ms.synchronization_button_signals.emit())

    def find_original_data_All(self, id):
        url = share.RURL.backendUrl + "/original/findByPid/" + id
        requests.encoding = 'utf-8'
        result = requests.request(method="GET", url=url, headers=share.token.headers)
        dataMap = json.loads(result.text)
        self.dataMap = dataMap
        # 源数据
        data = dataMap['data']
        dataHead = data[:2]
        self.dataList = []
        self.data = []
        # 表头处理赋值
        for index in range(len(dataHead)):
            data_Head_item = dataHead[index]["data"].replace('[', '').replace(']', '').replace(' ', '').split(",")
            self.dataList.append(data_Head_item)

        for index in range(len(data)):
            data_item = data[index]["data"].replace(']', '').replace(' ', '')[2:].split(",[")
            self.data.append(data_item)

    # 处理原数据表头
    def original_data_template(self):

        # 设置表头长度
        self.ui.tableWidget_1.setRowCount(2);
        self.ui.tableWidget_1.setColumnCount(len(self.dataList[0]));
        # 设置主体数据长度
        self.ui.tableWidget.setColumnCount(len(self.dataList[0]));
        # 建立滚动条联动信息
        self.ui.tableWidget.horizontalScrollBar().valueChanged.connect(
            lambda: self.global_ms.scrollbarOne_signals.emit(
                self.ui.tableWidget.horizontalScrollBar().value()))

        for index in range(len(self.dataList[0])):
            # 合并纵向表头
            if self.dataList[1][index] == '':
                self.ui.tableWidget_1.setSpan(0, index, 2, 1)
                self.ui.tableWidget_1.setItem(0, index, QTableWidgetItem(self.dataList[0][index]))
                #     设置内容居中
                self.ui.tableWidget_1.item(0, index).setTextAlignment(Qt.AlignCenter)

            # 合并横向表头
            if index + 1 < len(self.dataList[0]) and self.dataList[0][index + 1] == '' and self.dataList[0][
                index] != '':
                # 横向合并多少表头计数器 判断当前单元格后有多少空格，便向后合并多少
                count = 1
                for i in range(10):
                    try:
                        if self.dataList[0][index + count] == '':
                            count = count + 1
                        else:
                            break
                    except:
                        break
                # 合并表行
                self.ui.tableWidget_1.setSpan(0, index, 1, count)
                self.ui.tableWidget_1.setItem(0, index,QTableWidgetItem(self.dataList[0][index]))
                #     设置内容居中
                self.ui.tableWidget_1.item(0, index).setTextAlignment(Qt.AlignCenter)

            #             填报第二行表头
            if self.dataList[1][index] != '':
                self.ui.tableWidget_1.setItem(1, index,
                                              QTableWidgetItem(self.dataList[1][index]))
                #     设置内容居中
                self.ui.tableWidget_1.item(1, index).setTextAlignment(Qt.AlignCenter)

    # 源数据表头标题联动
    def original_data_scroll(self, coord):
        self.ui.tableWidget_1.horizontalScrollBar().setValue(coord)

    #    主体数据渲染
    def original_data_renderer(self):
        self.ui.tableWidget.setItem.setContentsMargins(0, 0, 0, 0);
        self.ui.tableWidget.tableWidget_3.setContentsMargins(0, 0, 0, 0);
        original_data = self.data[2:]
        # 设置主体数据条数
        self.ui.tableWidget.setRowCount(len(original_data));
        self.ui.tableWidget_3.setRowCount(len(original_data));
        for y in range(len(original_data)):
            for x in range(len(original_data[y])):
                if original_data[y][x] != '':
                    self.ui.tableWidget.setItem(y, x, QTableWidgetItem(original_data[y][x]))
                    self.ui.tableWidget_3.setItem(y, x, QTableWidgetItem(original_data[y][x]))
                else:
                    self.ui.tableWidget.setItem(y, x, QTableWidgetItem(''))
                    self.ui.tableWidget.tableWidget_3.setItem(y, x, QTableWidgetItem(''))

    # 单元格单击事件
    def item_alter(self):

        if self.flag == 0:
            return

        self.flag = 0
        item = self.ui.tableWidget.selectedItems()[0]
        rowIndex = self.ui.tableWidget.row(item);
        columnIndex = self.ui.tableWidget.column(item);
        text = item.text();
        data = [rowIndex, columnIndex, text]
        self.processing_dataList.append(data)

        # 判断当前修改数是（借方，贷方）还是修改数
        role = self.examine(columnIndex)

        if role == 0:
            # 获取调整数
            try:
                coordination = float(self.ui.tableWidget.item(rowIndex, columnIndex + 1).text())
                text = float(text)
                report_date = text + coordination
                self.ui.tableWidget.setItem(rowIndex, columnIndex + 2,
                                            QTableWidgetItem(str(report_date)))
                self.processing_dataList.append([rowIndex, columnIndex + 2, report_date])
            except:
                self.ui.tableWidget.setItem(rowIndex, columnIndex + 2, QTableWidgetItem(text))
                self.processing_dataList.append([rowIndex, columnIndex + 2, text])

        elif role == 1:
            # 获取借贷数
            try:
                coordination = float(self.ui.tableWidget.item(rowIndex, columnIndex - 1).text().replace(',',''))
                text = float(text)
                report_date = coordination + text
                self.ui.tableWidget.setItem(rowIndex, columnIndex + 1,
                                            QTableWidgetItem(str(format(report_date, ','))))
                self.processing_dataList.append([rowIndex, columnIndex + 1, str(format(report_date, ','))])
            except:
                self.ui.tableWidget.setItem(rowIndex, columnIndex + 1, QTableWidgetItem(str(format(float(text), ','))))
                self.processing_dataList.append([rowIndex, columnIndex + 1, str(format(float(text), ','))])
        else:
            pass

    # 判断当前修改数是（解放，贷方）还是修改数  0为（解放，贷方）   1为调整数   2为报表数
    def examine(self, columnIndex):
        for i in range(100):
            if columnIndex - 3 == 4 or columnIndex == 4:
                return 0
            elif columnIndex - 3 == 5 or columnIndex == 5:
                return 1
            columnIndex = columnIndex - 3
        return 2

    # 点击单元格
    def item_click(self):
        self.flag = 1

    # 同步按钮
    def synchronization_button(self):
        self.alter_data()

        # 核心功能代码就两行，可以加到需要的地方
        msg_box = QMessageBox(QMessageBox.Warning, '提示', '同步成功')
        msg_box.exec_()

    # 刷新按钮
    def refresh_button(self):
        # 源数据
        # self.data = dataExtract.readAll(share.urlList.source_data_url)[0]['data']
        self.dataList = self.data[1:3]
        self.original_data_renderer()

    # 修改数据
    def alter_data(self):
        # 记录已经更改的数据
        final_data = []

        for item in self.processing_dataList:
            # 当前修改的数据行
            dataitem = self.dataMap['data'][item[0]+2]
            # 待修改数据转数组
            dataup = dataitem['data'].replace('[[', '[').replace(']]', ']').replace(' ', '').split(',[')
            dataup[item[1]] = str(item[2]) + ']'

            dataStr = ""
            for itemOne in dataup:
                 dataStr = dataStr + itemOne + ',['

            # 将修改后的数据赋值
            self.dataMap['data'][item[0]+2]['data'] = '[' + dataStr[:len(dataStr)-2] + ']'
            final_data.append(self.dataMap['data'][item[0]+2])

        url = share.RURL.backendUrl + "/original"
        requests.encoding = 'utf-8'
        requests.request(method="PUT", url=url,json=final_data, headers=share.token.headers)

        self.processing_dataList = []

        # 重新拉取数据
        self.find_original_data_All(self.id)
        # 渲染数据
        self.original_data_renderer()
